import React, { useState, useEffect, Key } from 'react';
import { Modal, Drawer, message, Tag, Space } from 'antd';
import { connect, Dispatch } from 'umi';
import { DICT_LIST,
  DICT_ADD,
  DICT_UPDATE,
  DICT_DELETE, UPDATE_STATE } from '@/actions/dict';
import ProCard from '@ant-design/pro-card';
import ProDescriptions, { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import {PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import AGrid, { AGridButtonCallBackModel } from '@/components/SelfComp/AGrid';
import AButton from '@/components/SelfComp/AButton';
import { ConnectState } from '@/models/connect';
import { DataItem } from '@/models/common';
import { getItemValue } from '@/utils/commons';
import DictQueryForm from './components/DictQueryForm';
import AddDictModal from './components/AddDictModal';
import UpdateDictModal from './components/UpdateDictModal';
import { DictItem } from './data';

interface DictListProps {
  dispatch: Dispatch;
  dictList: DictItem[],
  total: number,
  loading: boolean;
  pageSize: number;
  addLoading: boolean;
  updateLoading: boolean;
  deleteLoading: boolean;
  editFlagData: DataItem[];
  statusData: DataItem[];
}

const EMPTY_DICT: DictItem = {
  dictId: '',
  dictName: '',
  dictDesc: '',
  dictItemName: '',
  dictItemDesc: '',
  status: '',
  editFlag: '',
}

/**
 * 字典列表管理
 * @param props 属性
 * @returns 字典列表
 */
const DictList: React.FC<DictListProps> = (props) => {
  const code = 'dict-list';
  const { dictList, loading, total, addLoading, updateLoading, deleteLoading, editFlagData, statusData } = props;
  const [addModalVisible, handleAddModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [row, setRow] = useState<DictItem>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [selectedRows, setSelectedRows] = useState<DictItem[]>([]);
  const [queryParam, setQueryParam] = useState<DictItem>(EMPTY_DICT);
  const [pageSize, setPageSize] = useState<number>(10);
  const [addFormData, setAddFormData] = useState<DictItem>(EMPTY_DICT);
  const [dictFormData, setDictFormData] = useState<DictItem>(EMPTY_DICT);
  const rowKey = (record: DictItem) => {
    return record.dictId;
  }
  const pkField = 'dictId';
  const columns = [
    {
      title: '字典描述',
      dataIndex: 'dictDesc',
      render: (text: string, record: DictItem, index: number) => {
        return <a onClick={() => setRow(record)}>{text}</a>;
      },
    },
    {
      title: '字典名',
      dataIndex: 'dictName',
      // width: 150
    },
    {
      title: '字典项',
      dataIndex: 'dictItemName',
      // width: 150
    },
    {
      title: '字典项描述',
      dataIndex: 'dictItemDesc',
      // width: 150
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (text: string, record: DictItem, index: number) => dictStatusFunc(record),
      // width: 70
    },
    {
      title: '是否可编辑',
      dataIndex: 'editFlag',
      // width: 70
    }
  ];

  useEffect(() => {
    console.info('DictList.useEffect');
    // fetchAllDict(1, 10, queryParam);
    return () => {
      const { dispatch } = props;
      dispatch(UPDATE_STATE({
        rows: [],
        total: 0
      }));
    }
  }, []);

  const dictStatusFunc = (record: DictItem) => {
    const { statusData } = props;
    const { status } = record;
    const value = getItemValue(statusData, status);
    if (status === '1') {
      return <Tag color='error'>{value}</Tag>;
    }
    return <Tag color='processing'>{value}</Tag>;
  }

  /**
   * 查询满足条件的数据字典
   */
  const handleQuery = (record: DictItem) => {
    console.info('DictList.handleQuery');
    console.info(record);
    const queryParam = {
      ...record
    };
    // 查询条件保存起来，方便点击页码时使用
    // setState回调方法，保证先更新state
    fetchAllDict(1, pageSize, queryParam);
  }

  const handleReset = () => {
    // 是否清空表格
  }

  /**
   * 分页查询系统参数信息
   * @param {*} pageNum 页码
   * @param {*} pageSize 每页记录条数
   */
  const fetchAllDict = (pageNum: number, pageSize: number, queryParam: DictItem) => {
    const { dispatch } = props;
    dispatch(DICT_LIST({
      ...queryParam,
      pageSize,
      pageNum
    }));
  }

  /**
   * 删除字典，支持多笔删除
   */
  const deleteDicts = async () => {
    const { dispatch } = props;
    const dictIds = [...selectedRowKeys]
    const res = await dispatch(DICT_DELETE(dictIds));
    if (res) {
      setSelectedRowKeys([]);
      setSelectedRows([]);
      dispatch(DICT_LIST({
        ...queryParam,
        pageSize,
        pageNum: 1,
      }));
    }
  }

  /**
   * 处理按钮点击回调事件
   * @param {*} payload 数据包
   */
  const handleBtnCallBack = (callBackModel: AGridButtonCallBackModel<DictItem>) => {
    console.log('handleBtnCallBack');
    console.log(callBackModel);
    // btn 按钮
    // keys 表格勾选数组
    const { btn } = callBackModel;
    const { alias } = btn;
    // 新增
    if (alias === 'add') {
      const { keys } = callBackModel;
      if (keys && keys.length > 1) {
        message.warn('新增时最多只允许选择一条数据当父节点！');
        return;
      }
      // 选中一条，可以将字典名当父节点使用
      if (keys && keys.length === 1) {
        const { rows } = callBackModel;
        openAddDictModal(rows);
        return;
      }
      openAddDictModal(undefined);
      return;
    }
    // 修改
    if (alias === 'edit') {
      const { rows } = callBackModel;
      setDictFormData(rows[0]);
      handleUpdateModalVisible(true);
      return;
    }
    // 删除
    if (alias === 'delete') {
      const { keys } = callBackModel;
      // 调用删除服务，删除勾选数据
      const dictId= keys[0];
      deleteDict(dictId);
      return;
    }
  }

  /**
   * 删除字典，暂时只支持单笔删除
   * @param dictId 字典id
   */
  const deleteDict = async (dictId: Key) => {
    const { dispatch } = props;
    const dictIds = [dictId]
    const res = await dispatch(DICT_DELETE(dictIds));
    if (res) {
      dispatch(DICT_LIST({
        ...queryParam,
        pageSize,
        pageNum: 1,
      }));
    }
  }

  /**
   * 表格勾选回调函数
   * @param {*} rows 表格选中数据集合
   */
  const onSelectRow = (keys: React.Key[], rows: DictItem[]) => {
    setSelectedRowKeys(keys);
    setSelectedRows(rows);
  };

  /**
   * 页码改变的回调，参数是改变后的页码及每页条数
   * @param page 改变后的页码，上送服务器端
   * @param pageSize 每页数据条数
   */
  const onPageNumAndSizeChange = (page: number, pageSize: number) => {
    console.log(page, pageSize);
    setPageSize(pageSize);
    fetchAllDict(page, pageSize, queryParam);
  };

  const openAddDictModal = (records: DictItem[] | undefined) => {
    console.info('openAddDictModal');
    console.info(records);
    if (records) {
      const row = records[0];
      const addFormData = {
        ...row
      };
      setAddFormData(addFormData);
      handleAddModalVisible(true);
    } else {
      handleAddModalVisible(true);
    }
  }

  const handleAddModal = async (record: DictItem) => {
    console.log(record);
    const { dispatch } = props;
    console.info(dispatch);
    const res = await dispatch(DICT_ADD(record));
    console.info(res);
    if (res) {
      handleAddModalVisible(false);
      setAddFormData(EMPTY_DICT);
      fetchAllDict(1, pageSize, queryParam);
    }
  }

  const handleAddModalCancel = () => {
    handleAddModalVisible(false);
  };

  /**
   * 更新面板的确定事件
   * @param {*} record 更新表单
   */
  const handleUpdateModal = async (record: DictItem) => {
    console.log('handleUpdateModalOk');
    console.log(record);
    console.info(dictFormData);
    const { dispatch } = props;
    const res = await dispatch(DICT_UPDATE(record));
    console.info(res);
    if (res) {
      handleUpdateModalVisible(false);
      setDictFormData(EMPTY_DICT);
      fetchAllDict(1, pageSize, queryParam);
    }
  }

  const handleUpdateModalCancel = () => {
    handleUpdateModalVisible(false);
    setDictFormData(EMPTY_DICT);
  };

  return (
    <PageContainer>
      <Space direction='vertical' size='middle' style={{ display: 'flex' }}>
        <ProCard title="查询条件" headerBordered>
          <DictQueryForm
            colon={false}
            loading={loading}
            onSubmit={(record) => {
              setQueryParam(record);
              handleQuery(record);
            }}
            onReset={handleReset}
          />
        </ProCard>
        <ProCard>
          <AGrid
            code={code}
            btnCallBack={handleBtnCallBack}
            columns={columns}
            rowKey={rowKey}
            pkField={pkField}
            dataSource={dictList}
            loading={loading}
            total={total}
            onSelectRow={onSelectRow}
            onPageNumAndSizeChange={onPageNumAndSizeChange}
          />
        </ProCard>
      </Space>
      {selectedRows?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a style={{ fontWeight: 600 }}>{selectedRows.length}</a>{' '}
              项
              &nbsp;&nbsp;
            </div>
          }
        >
          <AButton
            type='primary'
            code='batchDel'
            pageCode={code}
            name='批量删除'
            loading={deleteLoading}
            onClick={deleteDicts}
          />
        </FooterToolbar>
      )}
      {
        !addModalVisible ? null :
        <AddDictModal
          editFlagData={editFlagData}
          statusData={statusData}
          colon={false}
          modalTitle='新增字典项'
          modalWidth={1000}
          modalVisible={addModalVisible}
          loading={addLoading}
          formData={addFormData}
          onHandlerOK={handleAddModal}
          onHandlerCancel={handleAddModalCancel}
        />
      }
      {
        !updateModalVisible ? null :
        <UpdateDictModal
          editFlagData={editFlagData}
          statusData={statusData}
          colon={false}
          modalTitle=''
          modalWidth={1000}
          modalVisible={updateModalVisible}
          flag='edit'
          loading={updateLoading}
          formData={dictFormData}
          onHandlerOK={handleUpdateModal}
          onHandlerCancel={handleUpdateModalCancel}
        />
      }
      <Drawer
        width={600}
        open={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.dictId && (
          <ProDescriptions<DictItem>
            column={2}
            title={row?.dictName}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.dictId,
            }}
            columns={columns as ProDescriptionsItemProps<DictItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};


export default connect((state: ConnectState) => ({
  dictList: state.dicts.rows,
  total: state.dicts.total,
  editFlagData: state.dicts.editFlagData,
  statusData: state.dicts.statusData,
  loading: state.loading.effects['dicts/fetchAllDict'],
  addLoading: state.loading.effects['dicts/addDict'],
  updateLoading: state.loading.effects['dicts/updateDict'],
  deleteLoading: state.loading.effects['dicts/deleteDicts'],
}))(DictList);